package com.xushi.scheduler;

import com.xushi.bean.ActivityStateBean;
import com.xushi.bean.State;
import com.xushi.model.Activity;
import com.xushi.service.ActivityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.List;

@Component
public class ScheduledTasks {

    // @Resource默认按名字装配，找不到则按类型。如果指定name字段，只会按名字找
    // @Autowired默认按类型，可以与@Qualifier一起用来指定名字找
    @Resource
    private ActivityService activityService;

    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(cron = "0 */10 * * * *")
    public void checkAndUpdateActivityState() {
        try {
            List<Activity> activityList = activityService.getActiveActivities();
            activityList.forEach(activity -> {
                if (ActivityStateBean.isActivityEnded(activity)) {
                    activity.setState(State.INACTIVE.getState());
                    activityService.updateActivity(activity);
                }
            });
            log.info("定时更新");
        } catch (Exception e) {
            log.error("更新过期活动失败", e);
        }
    }
}
